<template>
  <div>

    <div class="card" style="margin-bottom: 5px;">
      <el-input v-model="data.itemName" style="width: 300px; margin-right: 10px" placeholder="请输入名称查询"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
      </div>
      <el-table :data="data.tableData" stripe>
        <el-table-column label="商品名称" prop="itemName"></el-table-column>
        <el-table-column label="商品价格" prop="itemPrice"></el-table-column>
        <el-table-column label="商品图片">
          <template #default="scope">
            <el-image :src="`https://zizi-1325809325.cos.ap-guangzhou.myqcloud.com/商品列表/List/${scope.row.itemImg}.jpg`"
              style="width: 40px; height: 40px; border-radius: 50%"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="商品库存" prop="itemStock">
          <template #default="scope">
            <span v-if="scope.row.role === 'ADMIN'">管理员</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card">
      <el-pagination background layout="prev, pager, next" v-model:page-size="data.pageSize"
        v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <el-dialog title="信息" width="40%" v-model="data.formVisible" :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" label-width="100px" style="padding-right: 50px">
        <el-form-item label="商品主图" prop="avatar">
          <el-upload action="#" :show-file-list="false" :on-change="handleChange"
            :auto-upload="false">
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品名称" prop="itemName">
          <el-input v-model="form.itemName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品价格" prop="itemPrice">
          <el-input v-model="form.itemPrice" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品库存" prop="itemStock">
          <el-input v-model="form.itemStock" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品描述" prop="itemDesc">
          <el-input v-model="form.itemDesc" autocomplete="off" />
        </el-form-item>
        <el-form-item label="商品类别">
          <el-select v-model="value1" placeholder="一级类别" size="small" style="width: 15vh;margin-right: 2vh;"
            @change="handleFirstCategoryChange">
            <el-option v-for="item in options1" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-select v-model="value2" placeholder="二级类别" size="small" style="width: 15vh;margin-right: 2vh;">
            <el-option v-for="item in subOptions2" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
          <el-input style="width: 15vh;height: 25px;margin-right: 2vh;" v-model="value3" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">上 架</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import request from "@/utils/request";
import { reactive } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { ref, computed } from "vue";
import axios from "axios";

// 文件上传的接口地址
const uploadUrl = import.meta.env.VITE_BASE_URL + '/files/upload'
const value1 = ref('')
const value2 = ref('')
const value3 = ref('')

const options1 = [
  {
    label: '水果',
    value: 'sg',
  },
  {
    label: '禽畜肉蛋',
    value: 'qcrd',
  },
  {
    label: '农副加工',
    value: 'nfjg',
  },
  {
    label: '农民工具',
    value: 'nmgj',
  },
  {
    label: '粮油米面',
    value: 'lymm',
  },
  {
    label: '中药材',
    value: 'zyc',
  },
  {
    label: '种子种苗',
    value: 'zzzm',
  },
  {
    label: '水产',
    value: 'shuic',
  },
  {
    label: '蔬菜',
    value: 'sc',
  },
  {
    label: '苗木花草',
    value: 'mmhc',
  }
]

const categoryMap = {
  'sg': [
    { label: '核果仁果', value: 'hgrg' },
    { label: '瓜果', value: 'gg' },
    { label: '浆果', value: 'jg' },
    { label: '柑橘', value1: 'gj' },
    { label: '热带水果', value: 'rdsg' },
    // 其他水果子类别
  ],
  'qcrd': [
    { label: '禽畜苗', value: 'qcm' },
    { label: '肉', value: 'r' },
    { label: '蛋', value: 'd' },
    { label: '活畜', value: 'hc' },
    { label: '特种肉', value: 'tzr' },
    // 其他禽畜肉蛋子类别
  ],
  'nfjg': [
    { label: '干果坚果', value: 'ggjn' },
    { label: '茶叶', value: 'cy' },
    { label: '肉制品', value: 'rzp' },
    { label: '水产加工', value: 'scjg' },
    { label: '营养滋补', value: 'yyzb' },
    { label: '速食品', value: 'sps' },
  ],
  'nmgj': [
    { label: '农用机械设备', value: 'nyjxq' },
    { label: '肥料', value: 'fl' },
    { label: '农药', value: 'ny' },
    { label: '饲料', value: 'sl' },
    { label: '农用百货', value: 'nybh' },
    { label: '排灌设备', value: 'pgsb' }
  ],
  'lymm': [
    { label: '食用油', value: 'syx' },
    { label: '调味品', value: 'twp' },
    { label: '香辛料', value: 'xxl' },
    { label: '谷物淀粉', value: 'gwdf' },
    { label: '豆制品', value: 'dzp' },
    { label: '面食米食', value: 'msmm' }
  ],
  'zzzm': [
    { label: '水果种苗', value: 'sgzm' },
    { label: '花草类种子', value: 'hclzz' },
    { label: '蔬菜种子', value: 'sczz' },
    { label: '水果类种子', value: 'sglzz' },
    { label: '粮油类种子', value: 'lylzz' },
  ],
  'mmhc': [
    { label: '乔木', value: 'qm' },
    { label: '灌木', value: 'gm' },
    { label: '竹类植物', value: 'zlzw' },
    { label: '棕榈类植物', value: 'zllzw' },
    { label: '水生植物', value: 'sszw' },
    { label: '藤本植物', value: 'tbzw' },
  ],
  'sc': [
    { label: '葱姜蒜', value: 'cjs' },
    { label: '根茎菜', value: 'gjc' },
    { label: '叶菜', value: 'yc' },
    { label: '豆菜', value: 'dc' },
    { label: '茄果菜', value: 'qgc' },
    { label: '食用菌', value: 'syj' },
  ],
  'shuic': [
    { label: '水产种苗', value: 'sczm' },
    { label: '虾', value: 'xia' },
    { label: '贝', value: 'b' },
    { label: '食用鱼', value: 'syy' },
    { label: '蟹', value: 'xie' },
    { label: '软体', value: 'rt' },
  ],
  'zyc': [
    { label: '滋补药材', value: 'zbyc' },
    { label: '菌藻', value: 'jz' },
    { label: '根茎', value: 'gj' },
    { label: '叶', value: 'ye' },
    { label: '果实籽仁', value: 'gszr' },
    { label: '树皮', value: 'shup' },
  ]
};


const subOptions2 = computed(() => {
  return categoryMap[value1.value] || [];
});

const subOptions3 = computed(() => {
  return subCategoryMap[value2.value] || [];
});

const handleFirstCategoryChange = (value) => {
  value2.value = ''; // 重置二级类别的值
  value3.value = ''; // 重置三级类别的值
};

const handleSecondCategoryChange = (value) => {
  value3.value = ''; // 重置三级类别的值
};

const data = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0,
  formVisible: false,
  form: {},
  tableData: [],
  name: null
})


// 分页查询
const load = () => {
  request.get('/farmer/selectItemPage/R001', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      itemName: data.itemName
    }
  }).then(res => {
    data.tableData = res.data?.list
    data.total = res.data?.total
  })
}

// 新增
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}

// 编辑
const handleEdit = (row) => {
  form.value = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}


const form = ref({
  itemName: '',
  itemPrice: null,
  itemStock: null,
  itemDesc: '',
  itemCategory: '',
  itemType: '',
  itemClass: '',
  avatar: null
})


const handleChange = (response) => {
  form.value.avatar = response.raw;
  console.log(form.value.avatar);
}

// 弹窗保存
const save = () => {
  const formData = new FormData();

  form.value.itemCategory = value1.value
  form.value.itemType = value2.value
  form.value.itemClass = value3.value

  formData.append('file', form.value.avatar);
  formData.append('itemName', form.value.itemName);
  formData.append('itemPrice', form.value.itemPrice);
  formData.append('itemStock', form.value.itemStock);
  formData.append('itemDesc', form.value.itemDesc);
  formData.append('itemCategory', form.value.itemCategory);
  formData.append('itemType', form.value.itemType);
  formData.append('itemClass', form.value.itemClass);
  console.log(formData);

  axios.post('http://localhost:9090/farmer/ItemUpload', formData,{
    Headers:{
      'Content-Type': 'multipart/form-data'
    }
  })
    .then(res => {
      ElMessage.success('上传成功');
    }).catch(err => {
      ElMessage.error('上传失败');
    })
    data.formVisible = false;
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(res => {
    request.delete('/admin/delete/' + id).then(res => {
      if (res.code === '200') {
        load()
        ElMessage.success('操作成功')
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => { })
}

// 重置
const reset = () => {
  data.form.itemName = null
  load()
}

load()
</script>